package pers.yd.springbootmvc.controller;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yudi
 */
@RestController
@RequestMapping("/movie-suggest")
public class MoviesSuggestController {

    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping
    public List<String> getMoviesSuggest(String prefix){
        List<String> ans = new ArrayList<>();
        CompletionSuggestionBuilder completionSuggestionBuilder = new CompletionSuggestionBuilder("title")
                .prefix(prefix)
                .skipDuplicates(true)
                .size(10);
        SuggestBuilder suggestBuilder = new SuggestBuilder().addSuggestion("title_suggest", completionSuggestionBuilder);

        SearchRequestBuilder requestBuilder = elasticsearchTemplate.getClient()
                .prepareSearch("movies")
                .suggest(suggestBuilder)
                .setFetchSource(false);

        SearchResponse response = requestBuilder.get();

        Suggest suggestions = response.getSuggest();

        Suggest.Suggestion suggestion = suggestions.getSuggestion("title_suggest");

        List<CompletionSuggestion.Entry> entries = suggestion.getEntries();

        entries.forEach(entry -> {
            List<CompletionSuggestion.Entry.Option> options = entry.getOptions();
            options.forEach(op -> {
                ans.add(op.getText().toString());
            });
        });

        return ans;
    }

}
